<template>
  <div class="container">
    <list-title title-text="项目信息" :show-button="false" class="title" />

    <a-form
      ref="projectRef"
      :model="formData"
      :rules="rules"
      :disabled="isReadonly"
      auto-label-width
    >
      <a-row :gutter="44" justify="center">
        <a-col :span="8">
          <a-form-item field="name" label="项目名称" validate-trigger="input">
            <a-input v-model="formData.name" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            field="code"
            label="项目编码"
            validate-trigger="input"
            disabled
          >
            <a-input v-model="formData.code" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="44" justify="center">
        <a-col :span="8">
          <a-form-item field="budget" label="项目预算" validate-trigger="input">
            <a-input v-model="formData.budget" placeholder="请输入">
              <template #append>万元</template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="type" label="项目类型" validate-trigger="input">
            <a-select v-model="formData.type" placeholder="请选择">
              <a-option
                v-for="type in projectTypes"
                :key="type.value + type.label"
                :value="type.value"
                :label="type.label"
              ></a-option
            ></a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="44" justify="center">
        <a-col :span="8">
          <a-form-item
            field="protemId"
            label="项目模版"
            validate-trigger="input"
          >
            <a-select v-model="formData.protemId" placeholder="请选择" disabled>
              <a-option
                v-for="template in projectTemplate"
                :key="template.id + template.name"
                :value="template.id"
                :label="template.name"
              ></a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            field="rangeDate"
            label="项目时间"
            validate-trigger="input"
          >
            <a-range-picker
              v-model="formData.rangeDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleDateChange"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="44" justify="center">
        <a-col :span="16">
          <a-form-item
            field="description"
            label="项目描述"
            validate-trigger="input"
          >
            <a-textarea
              v-model="formData.description"
              :auto-size="{
                minRows: 2,
                maxRows: 5,
              }"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="44" justify="center">
        <a-col :span="16" style="text-align: right">
          <a-button
            v-if="isReadonly"
            type="primary"
            @click="changeReadonly(false)"
            >编辑</a-button
          >
          <a-space v-else>
            <a-button type="outline" @click="changeReadonly(true)"
              >取消</a-button
            >
            <a-button type="primary" @click="handleOk">确定</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { projectTypes } from '@/directionary/project';
  import { getProjectList, ProjectListParams } from '@/api/project';
  import { ProjectRecord, queryProjectDetail, updateProject } from './api';
  import ListTitle from '../components/list-title.vue';

  const route = useRoute();
  const projectId = computed(() => {
    return String(route?.params?.projectId);
  });

  const isReadonly = ref(true);
  const projectRef = ref<FormInstance>();
  const emptyProject: ProjectRecord = {
    id: projectId.value,
    name: '',
    code: '',
    budget: '',
    type: 0,
    protemId: '',
    planStart: '',
    planEnd: '',
    description: '',
    rangeDate: [],
  };
  const formData = ref<ProjectRecord>(emptyProject);

  const rules = ref({
    name: [
      {
        required: true,
        message: '请输入项目名称',
      },
    ],
    code: [
      {
        required: true,
        message: '请输入项目编码',
      },
    ],
    type: [
      {
        required: true,
        message: '请选择项目类型',
      },
    ],
    budget: [
      {
        required: true,
        message: '请输入项目预算',
      },
      { type: 'number', positive: true, message: '请输入正数' },
    ],
    rangeDate: [
      {
        required: true,
        message: '请选择项目日期',
      },
    ],
    description: [
      {
        maxLength: 500,
        message: '最多不超过500字',
      },
    ],
  });

  // 处理项目时间变化
  const handleDateChange = (time: any) => {
    if (time && time.length === 2) {
      [formData.value.planStart, formData.value.planEnd] = time;
    } else {
      formData.value.planStart = '';
      formData.value.planEnd = '';
    }
  };

  // 查询项目详细信息
  const getProjectDetail = () => {
    const params = {
      id: projectId.value,
    };
    queryProjectDetail(params)
      .then((res) => {
        formData.value = res.data;
        formData.value.rangeDate = [res.data.planStart, res.data.planEnd];
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      });
  };

  // 项目模版
  const projectTemplate = ref<ProjectRecord[]>([]);
  // 获取所有项目模版
  const getTemplateList = () => {
    const params: ProjectListParams = {
      pageNo: 1,
      pageSize: 100000,
      projectType: 1,
    };
    getProjectList(params).then((res: any) => {
      if (res.code === 8000000) {
        projectTemplate.value = res.data?.list || [];
      }
    });
  };

  // 编辑/取消编辑按钮点击事件
  const changeReadonly = (readonly: boolean) => {
    isReadonly.value = readonly;
  };

  // 调用接口修改项目信息
  const handleEdit = async () => {
    try {
      const params = {
        ...formData.value,
      };
      delete params.rangeDate;
      const res = await updateProject(params);
      return !!res.status;
    } catch (error) {
      return false;
    }
  };

  // 确定按钮点击事件
  const handleOk = async (done: any) => {
    const res = await projectRef.value?.validate();
    if (!res) {
      const flg = await handleEdit();
      if (flg) {
        Message.success('编辑成功');
        isReadonly.value = true;
      }
      done();
    }
  };

  getProjectDetail();
  getTemplateList();
</script>

<style lang="less" scoped>
  .container {
    height: calc(100vh - 156px);
  }
  .title {
    margin: 8px 0 24px 0;
  }

  :deep(.arco-picker-range) {
    width: 100%;
  }
</style>
